import os

from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from utils.work_log import get_logger

if os.environ.get('MIGONG') == 'PRODUCTION':
    engine = create_engine('mysql+mysqlconnector://migong:2wo}sneuy7ry*apr@10.9.131.114:3306/migong_dev',
                           encoding='utf8',
                           max_overflow=0,
                           pool_size=1,
                           pool_timeout=30,
                           pool_recycle=-1,
                           pool_pre_ping=True)
else:
    engine = create_engine('mysql+mysqlconnector://migong:2wo}sneuy7ry*apr@106.75.47.179:13306/migong_dev',
                           encoding='utf8',
                           max_overflow=0,
                           pool_size=1,
                           pool_timeout=30,
                           pool_recycle=-1,
                           pool_pre_ping=True)

Base = declarative_base()
metadata = MetaData(bind=engine)
Session = sessionmaker(bind=engine)

log = get_logger(__name__)


def get_session():
    global session
    if session is None:
        session = Session()
    return session


def rollback_session():
    global session
    if session is not None:
        session.rollback()
        return True
    else:
        return False


def close_session():
    global session
    if session is not None:
        session.close()
        return True
    else:
        return False


session = Session()
